package com.hougong.im.httpcontroller;

import com.hougong.im.body.httpresponse.MyBaseInfoVo;
import com.hougong.im.body.httpresponse.MyFriendListVo;
import com.hougong.im.body.httpresponse.PersonMsgUnreadVo;
import com.hougong.im.entity.ChatGroup;
import com.hougong.im.entity.ChatUser;
import com.hougong.im.entity.Member;
import com.hougong.im.mapper.*;
import com.hougong.im.pool.ConnPool;
import com.hougong.im.utils.DateUtils;
import com.hougong.im.utils.FileUtils;
import com.hougong.im.utils.JwtUtils;
import com.hougong.im.utils.R;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * 账号相关的
 */
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private ChatUserMapper chatUserMapper;
    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private ApplyAddfriendMapper applyAddfriendMapper;

    @Autowired
    private PersonMessageMapper personMessageMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private ChatGroupMapper groupMapper;
    @Autowired
    private GroupMessageMapper groupMessageMapper;
    @Autowired
    private GroupMessageMemberMapper groupMessageMemberMapper;

    /**
     * 注册
     * @param request
     * @return
     */
    @RequestMapping("/register")
    @Transactional
    public R register(@RequestParam(value = "image",required = false) MultipartFile file,HttpServletRequest request) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String nickname = request.getParameter("nickname");
        List<ChatUser> chatUsers = chatUserMapper.selectByUserName(username);
        if(chatUsers==null || chatUsers.size()==0){
            List<ChatUser> chatUsers_phone = chatUserMapper.selectByPhone(phone);
            if(chatUsers_phone==null || chatUsers_phone.size()==0){
                if(password.length()>=6){
                    if(nickname==null || nickname.length()==0 || nickname.trim().equals("")){
                        return R.error("昵称请设置一位以上");
                    }else {
                        ChatUser chatUser=new ChatUser();
                        chatUser.setUsername(username);
                        chatUser.setPassword(password);
                        chatUser.setPhone(phone);
                        chatUser.setNickname(nickname);
                        chatUser.setCity(11);
                        chatUser.setCreateTime(new Date());
                        if(file!=null){
                            String virtualPath=FileUtils.uploadFile(username,file);
                            chatUser.setAvatar(virtualPath);
                        }
                        Integer insert = chatUserMapper.insert(chatUser);
                        //进群
                        ChatGroup chatGroup = groupMapper.selectById(1L);
                        Member member=new Member();
                        member.setGroupId(1L);
                        member.setMemberId(chatUser.getId());
                        member.setCreateTime(new Date());
                        member.setGroupRemark(chatGroup.getName());
                        member.setIngroupRemark(chatUser.getUsername());
                        memberMapper.insert(member);

                        if(insert==1){
                            return R.ok();
                        }else {
                            return R.error("数据库保存失败");
                        }
                    }
                }else {
                   return R.error("密码请设置6位以上");
                }
            }else {
               return R.error("失败,手机号已被绑定过");
            }
        }else {
            return R.error("失败,用户名已被注册过！");
        }
    }

    @RequestMapping("/registertest")
    public R registerTest(@RequestParam("image") MultipartFile file,HttpServletRequest request) throws IOException {
        String username = request.getParameter("username");
        System.out.println("username "+username);
        String fileName = username+"_"+DateUtils.format(new Date(),"yyyyMMddHHmmss") +"_"+file.getOriginalFilename();
        file.transferTo(new File("d:\\"+fileName));
        return R.ok();
    }

    /**
     * 获取个人基本信息
     * @param request
     * @return
     */
    @RequestMapping("/mybaseinfo")
    public R getMyBaseInfo(HttpServletRequest request){
        String token = request.getParameter("token");
        Long tokenUid = JwtUtils.getTokenUid(token);
        MyBaseInfoVo myBaseInfo = chatUserMapper.selectMyBaseInfo(tokenUid);
        if(myBaseInfo!=null){
            return R.ok().put("mybaseinfo",myBaseInfo);
        }else {
            return R.error("不存在该用户!");
        }
    }

    @RequestMapping("/test")
    public R test(HttpServletRequest request){
        return R.ok("哈哈");
    }

    /***
     * 查看我的好友列表 ,第一次 获取的时候携带 未读数量
     * @param request
     * @return
     *
     * {"msg":"success","code":0,"newfriendunread":0,"friendlist":[{"uid":4,"username":"world","nickname":"测试账号世界","introduction":"我就是我，不一样的烟火","avatar":"/image/a.jpg","sex":0,"remark":"测试账号世界","onlinestatus":0,"unreadnum":0}]}
     */
    @RequestMapping("/myfriends")
    @Transactional
    public  R getMyFriends(HttpServletRequest request){
        String token = request.getParameter("token");
        String isfirst = request.getParameter("isfirst");
        Long currentUid = JwtUtils.getTokenUid(token);
        Integer newFriendUnread=null;
        List<PersonMsgUnreadVo> personUnreadMessageCountVo = null;
        Map<Long,Integer> mapCount=new HashMap<>();
        if(isfirst.equals("true")){
            //申请记录未读消息
            newFriendUnread = applyAddfriendMapper.selectUnreadCount(currentUid);
            personUnreadMessageCountVo = personMessageMapper.selectUnreadMessageCountMap(currentUid);
            if(personUnreadMessageCountVo!=null && personUnreadMessageCountVo.size()>0){
                for(PersonMsgUnreadVo unreadVo:personUnreadMessageCountVo){
                    mapCount.put(unreadVo.getFid(),unreadVo.getNum());
                }
            }
        }
        List<MyFriendListVo> myFriends = friendMapper.findMyFriends(currentUid);
        for(MyFriendListVo friendListVo:myFriends){
            Channel query = ConnPool.queryTCP(friendListVo.getUid());
            if(query!=null){
                friendListVo.setOnlinestatus(1);
            }else {
                friendListVo.setOnlinestatus(0);
            }
            if(isfirst.equals("true")){
                Integer unreadCount = mapCount.get(friendListVo.getUid());
                if(unreadCount!=null){
                    friendListVo.setUnreadnum(unreadCount);
                }else {
                    friendListVo.setUnreadnum(0);
                }
            }
        }
        //在线在前离线在后
        Collections.sort(myFriends, new Comparator<MyFriendListVo>() {
            @Override
            public int compare(MyFriendListVo o1, MyFriendListVo o2) {
                return o2.getOnlinestatus()-o1.getOnlinestatus();
            }
        });
        return R.ok().put("newfriendunread",newFriendUnread).put("friendlist",myFriends);
    }

    @RequestMapping("/updatemyinfo")
    public R updateMyInfo(HttpServletRequest request) throws ParseException {
        String token = request.getParameter("token");
        Long tokenUid = JwtUtils.getTokenUid(token);
        ChatUser chatUser = chatUserMapper.selectById(tokenUid);
        String nickName = request.getParameter("nickname");
        Integer sex = Integer.parseInt(request.getParameter("sex")); //性别0女1男-1保密
        String introduction = request.getParameter("introduction");
        String birthday = request.getParameter("birthday");  //yyyy-mm-dd
        Date birthDate=DateUtils.parseDate(birthday,"yyyy-MM-dd");

        if(nickName!=null&&sex!=null){
            chatUser.setNickname(nickName);
            if(sex!=0 && sex!=1){
                sex=-1;
            }
            chatUser.setSex(sex);
            chatUser.setIntroduction(introduction);
            chatUser.setBirthday(birthDate);
            chatUserMapper.updateById(chatUser);
            return R.ok();
        }
        return R.error("数据格式不对");
    }

    @RequestMapping("/updatemyheadimg")
    public R updateMyHeadImg(@RequestParam("image") MultipartFile file,HttpServletRequest request) throws IOException {
        String token = request.getParameter("token");
        Long tokenUid = JwtUtils.getTokenUid(token);
        ChatUser chatUser = chatUserMapper.selectById(tokenUid);
        String path = FileUtils.uploadFile(chatUser.getUsername(), file);
        chatUser.setAvatar(path);
        Integer integer = chatUserMapper.updateById(chatUser);
        if(integer==1){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 获取我的群
     * @param request
     * @return
     */
    @RequestMapping("/mygroups")
    public R myGroups(HttpServletRequest request){
        String token = request.getParameter("token");
        Long tokenUid = JwtUtils.getTokenUid(token);
        Map map=new HashMap();
        map.put("member_id",tokenUid);
        List<Member> list = memberMapper.selectByMap(map);
        return  R.ok().put("groupList",list);
    }

}
